Plotly

What is Plotly

How can you use Plotly

Plotly for Python - Installation

To install Plotly's Python package, use the package manager pip inside your terminal.

pip install plotly

or

sudo pip install plotly

Initialize by writing

import plotly

The Plotly Syntax

  • Plotly charts are described declaratively with objects in plotly.graph_objs. These objects are basically Python dictionaries and lists.
  • All bits of information of a plotly plot is stored in a figure object consisting of a Data graph object and a Layout graph object.
    • Data stores style and data options associated with traces (a collection of data points meant to be plotted as a whole)
    • Layout stores information associated with the layout of the graph (axis, title, or annotations)

The Figure, Data and Layout Object

Figure:

  • A dictionary-like object
  • Valid keys
    • Data
    • Layout

Data

  • A list-like object of trace dictionary-like objects to be shown on one plotly figure
  • Ordering is important
  • Examples trace objects:
    • Scatter
    • Bar
    • ...

Layout

  • A dictionary-like object containing specifications of the layout of the plotly figure
  • Valid keys
    • Width
    • Height
    • ...

An Example for Figure, Data and Layout Object

import plotly.graph_objs as go

trace_1 = go.Scatter(                # Initialize the scatter trace object                         
        x=[1, 2, 3],                 # Set reference between trace's x coordinates and 2D cart. x axis
        y=[3, 1, 6],                 # Set reference between trace's y coordinates and 2D cart. y axis
        mode='markers')              # Mode of the scatter trace object (other modes: lines, text)
trace_2 = go.Scatter(                # Initialze a second scatter trace object
        x=[1, 2, 3],
        y=[2, 4, 5])    
data = [trace_1, trace_2]            # Create the data list-like object consisting of two traces

layout = Layout(title='Fig 0.3: Some Experiment') # Set the figures title

fig = Figure(data=data, layout=layout) # Make Figure object consisting of data and layout

Ploting the figure

  1. Offline Mode
    py.offline.init_notebook_mode() # run at the start of every notebook
    ...
    py.offline.iplot(fig)
    
  2. Online Mode
    import plotly.tools as tls
    tls.set_credentials_file(username="your_username", api_key="your_api_key") #Get these from signin in to Plotly
    py.iplot(fig, filename='s0_second-plot') # We are sending the plot first to plotly
    

Exercise

Take the plot from before and change the title of the x-axis to Some independent variable and the title of the y-axis to Some dependent variable. Hint: Use help(XAxis) and help(YAxis) and change the layout-object.

import plotly.graph_objs as go

trace_1 = go.Scatter(                
        x=[1, 2, 3],
        y=[3, 1, 6],
        mode='markers')
trace_2 = go.Scatter(
        x=[1, 2, 3],
        y=[2, 4, 5])    
data = [trace_1, trace_2]

layout = Layout(title='Fig 0.3: Some Experiment')

fig = Figure(data=data, layout=layout)

The Hello World Example for Offline Use

import plotly as py
py.offline.init_notebook_mode() # run at the start of every notebook
py.offline.iplot({
"data": [{
    "x": [1, 2, 3],
    "y": [4, 2, 5]
}],ß
"layout": {
    "title": "hello world"
}
})

Example - Bubble Charts

Bubble charts can be used for ....

In [ ]:
import plotly as py
import plotly.graph_objs as go
py.offline.init_notebook_mode() 

trace0 = go.Scatter(
    x=[1, 2, 3, 4],
    y=[10, 11, 12, 13],
    mode='markers',
    marker=dict(
        size=[40, 60, 80, 100],
    )
)
data = [trace0]
layout = go.Layout(
    showlegend=False,
    height=600,
    width=600,
)
fig = go.Figure(data=data, layout=layout)
# py.offline.plot(fig, filename='bubble_chart.html')
py.offline.iplot(fig)

Setting marker size, color, opacity and add a legend

In [ ]:
# Setting marker size, color, opacity and add a legend
import plotly as py
import plotly.graph_objs as go

data=[
    go.Scatter(
        x=[1, 2, 3, 4],
        y=[10, 11, 12, 13],
        mode='markers',
        marker=dict(
            color= [120, 125, 130, 135, 140],
            opacity=[1, 0.8, 0.6, 0.4],
            size=[40, 60, 80, 100],
            showscale=True
        )
    )
]

layout = go.Layout(
    showlegend=False,
    height=600,
    width=600,
)
fig = go.Figure(data=data, layout=layout)
# py.offline.plot(fig, filename='bubble_chart_colorlegend.html')
py.offline.iplot(fig)

Hover text with bubble charts

In [ ]:
# Hover text with bubble charts
import plotly as py
import plotly.graph_objs as go

data=[
    go.Scatter(
        x=[1, 2, 3, 4],
        y=[10, 11, 12, 13],
        text=['size: 40', 'size: 60', 'size: 80', 'size: 100'],
        mode='markers',
        marker=dict(
            color= [120, 125, 130, 135, 140],
            opacity=[1, 0.8, 0.6, 0.4],
            size=[40, 60, 80, 100],
            showscale=True
        )
    )
]

layout = go.Layout(
    showlegend=False,
    height=600,
    width=600,
)
fig = go.Figure(data=data, layout=layout)
# py.offline.plot(fig, filename='bubble_chart_hovertext.html')
py.offline.iplot(fig)

Time Series

In [8]:
# Simple Time Series Chart
import plotly as py
import plotly.graph_objs as go

from datetime import datetime
x = [
    datetime(year=2013, month=10, day=04),
    datetime(year=2013, month=11, day=05),
    datetime(year=2013, month=12, day=06)
]

data = [
    go.Scatter(
        x=x,
        y=[1, 3, 6]
    )
]
# py.offline.plot(data, filename='timeseries_simple.html')
py.offline.iplot(data)

Changing stuff (???)

In [9]:
data = [
    go.Scatter(
        x=['2013-10-04 22:23:00', '2013-11-04 22:23:00', '2013-12-04 22:23:00'],
        y=[1, 3, 6]
    )
]
# py.offline.plot(data, filename='timeseries_datestrings.html')
py.offline.iplot(data)

Bar Charts

In [ ]:
import plotly as py
import plotly.graph_objs as go

data = [
    go.Bar(
        x=['giraffes', 'orangutans', 'monkeys'],
        y=[20, 14, 23]
    )
]
#py.offline.plot(data, filename='barchart.html')
py.offline.iplot(data)

Grouped barcharts

In [ ]:
# Grouped barcharts
import plotly as py
import plotly.graph_objs as go

trace1 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[20, 14, 23],
    name='SF Zoo'
)
trace2 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[12, 18, 29],
    name='LA Zoo'
)
data = [trace1, trace2]
layout = go.Layout(
    barmode='group'
)
fig = go.Figure(data=data, layout=layout)
#py.offline.plot(fig, filename='barchart_grouped.html')
py.offline.iplot(fig)

Stacked barchars

In [5]:
# Stacked barchars
import plotly as py
import plotly.graph_objs as go

trace1 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[20, 14, 23],
    name='SF Zoo'
)
trace2 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[12, 18, 29],
    name='LA Zoo'
)
data = [trace1, trace2]
layout = go.Layout(
    barmode='stack'
)
fig = go.Figure(data=data, layout=layout)
#py.offline.plot(fig, filename='barchart_stacked.html')
py.offline.iplot(fig)

Barcharts with hover text

In [7]:
# Barcharts with hover text
import plotly as py
import plotly.graph_objs as go

trace0 = go.Bar(
    x=['Product A', 'Product B', 'Product C'],
    y=[20, 14, 23],
    text=['27% market share', '24% market share', '19% market share'],
    marker=dict(
        color='rgb(158,202,225)',
        line=dict(
            color='rgb(8,48,107)',
            width=1.5,
        )
    ),
    opacity=0.6
)
data = [trace0]
layout = go.Layout(
    title='January 2013 Sales Report',
)
fig = go.Figure(data=data, layout=layout)
#py.offline.plot(fig, filename='barchart_stacked_hover.html')
py.offline.iplot(fig)

Maps

In [5]:
#World Chloropleth Map
import plotly as py
import plotly.graph_objs as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')

data = [ dict(
        type = 'choropleth',
        locations = df['CODE'],
        z = df['GDP (BILLIONS)'],
        text = df['COUNTRY'],
        colorscale = [[0,"rgb(5, 10, 172)"],[0.35,"rgb(40, 60, 190)"],[0.5,"rgb(70, 100, 245)"],\
            [0.6,"rgb(90, 120, 245)"],[0.7,"rgb(106, 137, 247)"],[1,"rgb(220, 220, 220)"]],
        autocolorscale = False,
        reversescale = True,
        marker = dict(
            line = dict (
                color = 'rgb(180,180,180)',
                width = 0.5
            )
        ),
        colorbar = dict(
            autotick = False,
            tickprefix = '$',
            title = 'GDP<br>Billions US$'
        ),
    ) ]

layout = dict(
    title = '2014 Global GDP<br>Source: \
<a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
CIA World Factbook</a>',
    geo = dict(
        showframe = False,
        showcoastlines = False,
        projection = dict(
            type = 'Mercator'
        )
    )
)

fig = dict( data=data, layout=layout )
url = py.offline.iplot( fig, validate=False)

Chloropleth Inset Map

In [ ]:
#Chloropleth Inset Map
import plotly as py
import plotly.graph_objs as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_ebola.csv')
df.head()

cases = []
colors = ['rgb(239,243,255)','rgb(189,215,231)','rgb(107,174,214)','rgb(33,113,181)']
months = {6:'June',7:'July',8:'Aug',9:'Sept'}

for i in range(6,10)[::-1]:
    cases.append(go.Scattergeo(
        lon = df[ df['Month'] == i ]['Lon'], #-(max(range(6,10))-i),
        lat = df[ df['Month'] == i ]['Lat'],
        text = df[ df['Month'] == i ]['Value'],
        name = months[i],
        marker = dict(
            size = df[ df['Month'] == i ]['Value']/50,
            color = colors[i-6],
            line = dict(width = 0)
        ),
    ) )

cases[0]['text'] = df[ df['Month'] == 9 ]['Value'].map('{:.0f}'.format).astype(str)+' '+\
    df[ df['Month'] == 9 ]['Country']
cases[0]['mode'] = 'markers+text'
cases[0]['textposition'] = 'bottom center'

inset = [
    go.Choropleth(
        locationmode = 'country names',
        locations = df[ df['Month'] == 9 ]['Country'],
        z = df[ df['Month'] == 9 ]['Value'],
        text = df[ df['Month'] == 9 ]['Country'],
        colorscale = [[0,'rgb(0, 0, 0)'],[1,'rgb(0, 0, 0)']],
        autocolorscale = False,
        showscale = False,
        geo = 'geo2'
    ),
    go.Scattergeo(
        lon = [21.0936],
        lat = [7.1881],
        text = ['Africa'],
        mode = 'text',
        showlegend = False,
        geo = 'geo2'
    )
]

layout = go.Layout(
    title = 'Ebola cases reported by month in West Africa 2014<br> \
Source: <a href="https://data.hdx.rwlabs.org/dataset/rowca-ebola-cases">\
HDX</a>',
    geo = dict(
        resolution = 50,
        scope = 'africa',
        showframe = False,
        showcoastlines = True,
        showland = True,
        landcolor = "rgb(229, 229, 229)",
        countrycolor = "rgb(255, 255, 255)" ,
        coastlinecolor = "rgb(255, 255, 255)",
        projection = dict(
            type = 'Mercator'
        ),
        lonaxis = dict( range= [ -15.0, -5.0 ] ),
        lataxis = dict( range= [ 0.0, 12.0 ] ),
        domain = dict(
            x = [ 0, 1 ],
            y = [ 0, 1 ]
        )
    ),
    geo2 = dict(
        scope = 'africa',
        showframe = False,
        showland = True,
        landcolor = "rgb(229, 229, 229)",
        showcountries = False,
        domain = dict(
            x = [ 0, 0.6 ],
            y = [ 0, 0.6 ]
        ),
        bgcolor = 'rgba(255, 255, 255, 0.0)',
    ),
    legend = dict(
           traceorder = 'reversed'
    )
)

fig = go.Figure(layout=layout, data=cases+inset)
url = py.plot(fig, validate=False, filename='West Africa Ebola cases 2014')
In [ ]:
 
In [ ]: